﻿using System;

namespace ExceptionManagementStudy
{
    static class ExceptionChainStudy
    {
        internal static void Test()
        {
            AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            Level3();
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Console.WriteLine("UnhandledException:" +
            e.IsTerminating);
        }

        private static void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
        {
            Console.WriteLine("FirstChanceException" + e.Exception.Message);
        }

        private static void Level3()
        {
            try
            {
                Console.WriteLine("Level3 in try");
                Level2();
            }
            catch
            {
                Console.WriteLine("Level3 in catch");
                throw;
            }
            finally
            {
                Console.WriteLine("Level3 in finally");
            }
        }

        private static void Level2()
        {
            try
            {
                Console.WriteLine("Level2 in try");
                Level1();
            }
            catch
            {
                Console.WriteLine("Level2 in catch");
                throw;
            }
            finally
            {
                Console.WriteLine("Level2 in finally");
            }
        }

        private static void Level1()
        {
            try
            {
                Console.WriteLine("Level1 in try");
                throw new Exception("Level1");
            }
            catch
            {
                Console.WriteLine("Level1 in catch");
                throw;
            }
            finally
            {
                Console.WriteLine("Level1 in finally");
            }
        }
    }
}